<?php
/**
 * Created by JetBrains PhpStorm.
 * User: CAIXUDONG
 * Date: 11-6-15
 * Time: 下午4:10
 */
class UserModel extends Model{
    public $select_db = 'admin';

    public function isLogin(){

        if($_COOKIE[SITE_PREFIX.'user_id'] && $this->session()->get('user_id') == $_COOKIE[SITE_PREFIX.'user_id']){
            return true;
        }else{
            l('过期时候的COOKIE：'.$_COOKIE[SITE_PREFIX.'user_id'].'，SESSION：'.$this->session()->get('user_id'),'logout');
        }
        return false;
    }

    public function needLogin(){
        $is_login = $this->isLogin();
        if(!$is_login){
            if($this->input()->isAjax()){
                echo '{"statusCode":"301"}';
                exit;
            }else{
                redirect('login.php');
            }
        }
        if($this->session()->get('user_id')){
            return $this->getUserById($this->session()->get('user_id'));
        }
        return array();
    }

    //是否有权限
    public function isAction($action_name,$user_id = ''){
        $user_id = $user_id ? $user_id : $this->session()->get('user_id');

        $user_cate_ids = $this->getUserCateIds($user_id);

        $sql = "select cate_id from cates where lower(action) = :action";

        $action_id = $this->db()->getOne($sql,array('action'=>$action_name));

        if($action_id){

            if(in_array($action_id,$user_cate_ids)){
                return true;
            }else{
                echo '{"statusCode":"300","message":"对不起，您没有权限访问该页面！"}';
                exit;
            }

        }
//        else{
//            echo '{"statusCode":"300","message":"对不起，您访问的页面不存在！<br/>'.$action_name.'"}';
//            exit;
//        }
        
    }

    public function getUserById($user_id){
        $sql = "select * from users where user_id = :user_id";
        return $this->db()->getRow($sql,array('user_id'=>$user_id));
    }

    public function loginUser($username,$password){
        $sql = "select * from users where user_name = :user_name and password = :password";
        return $this->db()->getRow($sql,array('user_name'=>$username,'password'=>$password));
    }

    public function addUser($user_name,$password,$email = '' ,$tel = '',$real_name = '',$svn_user = ''){
        $sql = "insert into users(user_name,password,email,tel,svn_user,real_name,last_time,last_ip) values(:user_name,:password,:email,:tel,:svn_user,:real_name,now(),:last_ip)";
        $password = substr(md5($password.PASSWORD_PREFIX),0,16);
        $bindarr = array(
            'user_name'=>$user_name,
            'password'=>$password,
            'email'=>$email,
            'tel'=>$tel,
            'real_name'=>$real_name,
            'svn_user'=>$svn_user,
            'last_ip'=>return_ip(),
        );
        $this->db()->execute($sql,$bindarr);
        return $this->db()->lastInsertId();
    }

    public function updateUser($user_id,$user_name,$password,$email = '',$tel = '',$real_name = '',$svn_user = ''){
        $bindarr = array(
            'user_name'=>$user_name,
            'email'=>$email,
            'tel'=>$tel,
            'real_name'=>$real_name,
            'svn_user'=>$svn_user,
            'last_ip'=>return_ip(),
            'user_id'=>$user_id,
        );
        if($password){
            $sql = "update users set user_name = :user_name, password =:password ,email = :email, tel = :tel,real_name = :real_name,svn_user = :svn_user,last_ip = :last_ip where user_id = :user_id";
            $password = substr(md5($password.PASSWORD_PREFIX),0,16);
            $bindarr['password'] = $password;
        }else{
            $sql = "update users set user_name = :user_name, email = :email, tel = :tel,real_name = :real_name,svn_user = :svn_user,last_ip = :last_ip where user_id = :user_id";
        }
        $rs = $this->db()->execute($sql,$bindarr);
        return $rs->rowCount();
    }

    public function delUser($user_id){

        $sql = "delete from users where user_id = :user_id";

        $bindarr = array(
            'user_id'=>$user_id,
        );
        $rs = $this->db()->execute($sql,$bindarr);
        return $rs->rowCount();
    }

    public function getUserList($curr_page = 1 ,$per_page = 50,$user_name = ''){
        $where = ' 1 = 1 ';
        $bindarr = array();
        if($user_name){
            $where .= ' and u.user_name like :user_name';
            $bindarr['user_name'] = '%'.$user_name.'%';
        }
        $ret = $this->pager($curr_page, $per_page)
                ->ct('select count(*) from users u where '. $where ,$bindarr)
                ->rs("select u.*,group_concat(r.role_name) as role_names from users u left join user_has_roles ur on u.user_id = ur.user_id left join roles r on r.role_id = ur.role_id where ".$where." group by u.user_id order by u.user_id desc",$bindarr);
        return $ret;
    }

    public function getUsers(){
        $sql = "select * from users order by user_id desc";
        $ret = $this->db()->getAll($sql);
        return $ret;
    }

    public function getRoleUsers($role_id){

        $sql = "select * from users where user_id in(select distinct u.user_id from users u left join user_has_roles ur on u.user_id = ur.user_id where ur.role_id = :role_id or ur.role_id = 1) order by user_id desc";
        $ret = $this->db()->getAll($sql,array('role_id'=>$role_id));
        return $ret;
    }

    public function getTestUsers(){

        $sql = "select u.* from users u left join user_has_roles ur on u.user_id = ur.user_id where ur.role_id in(4,5)";
        
        $ret = $this->db()->getAll($sql);
        return $ret;
    }

    public function login($user_id){

        $sql = "update users set last_ip = :last_ip,last_time = :last_time where user_id = :user_id";
        $bindarr = array(
            'last_ip'=>return_ip(),
            'last_time'=>date('Y-m-d H:i:s'),
            'user_id'=>$user_id,
        );
        $rs = $this->db()->execute($sql,$bindarr);

        return $rs->rowCount();
    }

    public function getUserCates($user_id){

        $sql = "select * from cate_has_users where user_id = :user_id";

        $bindarr = array(
            'user_id'=>$user_id,
        );

        return $this->db()->getAll($sql,$bindarr);
    }

    public function getUserRoles($user_id){

        $sql = "select r.* from user_has_roles u left join roles r on u.role_id = r.role_id where user_id = :user_id";

        $bindarr = array(
            'user_id'=>$user_id,
        );

        return $this->db()->getAll($sql,$bindarr);
    }

    //获取用户所有的权限分类ID
    public function getUserCateIds($user_id){
        static $caches = array();

        if($caches[$user_id]){
            
            return $caches[$user_id];

        }else{

            $sql = "select cate_id from cate_has_roles cr left join user_has_roles ur on cr.role_id = ur.role_id where ur.user_id = :user_id";
            $rcate_ids = $this->db()->getOneAll($sql,array('user_id'=>$user_id));

            $sql = "select cate_id from cate_has_users where user_id = :user_id";

            $ucate_ids = $this->db()->getOneAll($sql,array('user_id'=>$user_id));

            $cate_ids = array_unique(array_merge($rcate_ids,$ucate_ids));

            $caches[$user_id] = $cate_ids;
            return $cate_ids;
        }
    }

    public function isSuperAdmin($user_id){
        $sql = "select count(*) from user_has_roles where user_id = :user_id and role_id = 1";
        return $this->db()->getOne($sql,array('user_id'=>$user_id));
    }

    public function updateUserName($user_id,$user_name){
        $sql = "update users set user_name = :user_name where user_id  = :user_id";
        $rs = $this->db()->execute($sql,array('user_name'=>$user_name,'user_id'=>$user_id));
        return $rs->rowCount();
    }
}
